﻿using Google.Protobuf.WellKnownTypes;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1.Tsp;
using Org.BouncyCastle.Asn1.X9;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using static log4net.Appender.RollingFileAppender;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;

namespace CloudApiServer.Controllers
{
    /// <summary>
    /// 国标处方中心接口控制器.
    /// </summary>
    [RoutePrefix("epc/api")]
    public class FsiEpcController : ApiController
    {


        /*接口*/
        /// <summary>
        /// 医保接口没找到的统一接口返回
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public IHttpActionResult FsiNotFound(HttpRequestMessage request)
        {
            string url = request.RequestUri.ToString();
            string Method = request.Method.ToString();
            string Errnum = LogHelper.GetErrornumber();
            try
            {
                FsiEpcHeader FsiHeader = new FsiEpcHeader
                {
                    code = 50000,
                    message =  $"[{Errnum}]调用国标处方中心自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加,当前请求入参：" + request.Content.ReadAsStringAsync().Result,
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                {
                    code = 50000,
                    message = $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace} " 
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 电子处方线下流转授权（人工核验） 身份登记
        /// </summary>
        /// <returns></returns>
        [Route("agentReqRxAuthReg")]
        [HttpPost]
        public async Task<IHttpActionResult> agentReqRxAuthReg(HttpRequestMessage request)
        {
            // 创建一个DataTable对象
            DataTable dt = new DataTable();
            // 定义数据库连接字符串
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            // 使用using语句创建MySqlConnection对象
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    // 判断接口是否被控制台停用
                    if (FsiDatainfo.stateFsiEpcApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }

                    // 打印处方中心入参
                    Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                    // 将入参转换为FsiRequestEpcHeader对象
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                    // 获取入参中的encData
                    string encData = fsiRequest.encData;
                    // 解密encData
                    string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    // 获取入参中的version和timestamp
                    string version = fsiRequest.version;
                    string timestamp = fsiRequest.timestamp.ToString();
                    // 打印解密后的入参
                    Console.WriteLine("处方中心入参解密：" + decData);

                    // 将解密后的入参转换为FsiRequestEpcAgentReqRxAuthRegInput对象
                    var AgentReqRxAuthRegInput = JsonConvert.DeserializeObject<FsiRequestEpcAgentReqRxAuthRegInput>(decData);

                    if (string.IsNullOrEmpty(AgentReqRxAuthRegInput.certno) 
                        || string.IsNullOrEmpty(AgentReqRxAuthRegInput.psnName) ||string.IsNullOrEmpty(AgentReqRxAuthRegInput.fixmedinsCode)
                        ||string.IsNullOrEmpty(AgentReqRxAuthRegInput.regerName) ||string.IsNullOrEmpty(AgentReqRxAuthRegInput.regerCertType)
                        ||string.IsNullOrEmpty(AgentReqRxAuthRegInput.regerCertno) || string.IsNullOrEmpty(AgentReqRxAuthRegInput.ipInfo)
                        ||string.IsNullOrEmpty(AgentReqRxAuthRegInput.psnCertType))
                    {
                        throw new Exception("参数校验失败：必填项字段校验失败，certno、psnName、psnCertType、fixmedinsCode、regerName、regerCertno、regerCertType、ipInfo字段不能为空！当前入参：" + decData);
                    }

                    var AgentReqRxAuthRegOutput = new FsiEpcAgentReqRxAuthRegOutputData
                    // 创建FsiEpcAgentReqRxAuthRegOutputData对象
                    {
                        regSn = Guid.NewGuid().ToString(),
                        datetime = DateTime.Now
                    };
                    /*出参加密*/
                    string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(AgentReqRxAuthRegOutput, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    // 将出参加密
                    /*加密结束*/
                    FsiEpcOutput<FsiEpcAgentReqRxAuthRegOutputData> signDto = new FsiEpcOutput<FsiEpcAgentReqRxAuthRegOutputData>
                    // 创建FsiEpcOutput对象
                    {
                        appId = FsiEpcTokeninfo.appId,
                        encType = "SM4",
                        signType = "SM2",
                        timestamp = fsiRequest.timestamp.ToString(),
                        data = AgentReqRxAuthRegOutput,
                        version = version,
                        key = FsiEpcTokeninfo.appSecret,

                    };
                    Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(AgentReqRxAuthRegOutput, Formatting.None));
                    // 打印准备签名验证的参数
                    Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                    // 打印完整的signDto参数
                    //签名
                    string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                    /*---------------解密部分-----------------*/
                    string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    // 解密出参
                    Console.WriteLine("解密：" + eeee);
                    // 打印解密后的出参
                    Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                    // 验签
                    Console.WriteLine("验签：" + isVerify);
                    // 打印验签结果
                    FsiEpcHeader FsiHeader = new FsiEpcHeader
                    // 创建FsiEpcHeader对象
                    {
                        code = 0,
                        appId = FsiEpcTokeninfo.appId,
                        encData = returnEncData,
                        signData = signData,
                        message = "success",
                        timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                    };
                    return Json(FsiHeader);
                    // 返回Json格式的FsiEpcHeader对象
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    // 获取错误编号
                    FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                    // 创建FsiEpcErrorHeader对象
                    {
                        code = 50000,
                        message = $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace} " 
                    };
                    LogHelper.Error( $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                    // 返回Json格式的FsiEpcErrorHeader对象
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    // 关闭数据库连接
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }


        /// <summary>
        /// 电子处方线下流转授权
        /// </summary>
        /// <returns></returns>
        [Route("fixmedins/rxAuthQuery")]
        [HttpPost]
        public async Task<IHttpActionResult> rxAuthQuery(HttpRequestMessage request)
        {
            DataTable dt = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiEpcApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }

                    Console.WriteLine("处方中心入参："+ request.Content.ReadAsStringAsync().Result);
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                    string encData = fsiRequest.encData;
                    string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    string version = fsiRequest.version;
                    string timestamp = fsiRequest.timestamp.ToString();
                    Console.WriteLine("处方中心入参解密：" + decData);

                    var RxAuthQueryInput = JsonConvert.DeserializeObject<FsiRequestEpcRxAuthQueryInput>(decData);
                    string certno = RxAuthQueryInput.certno;
                    string psnName = RxAuthQueryInput.psnName;

                    string ecToken = RxAuthQueryInput.ecToken;
                    string regSn = RxAuthQueryInput.regSn;
                    if(!string.IsNullOrEmpty(ecToken) && !string.IsNullOrEmpty(regSn))
                    {
                        throw new Exception("参数校验失败：传入的患者电子凭证token和人工审核登记流水号不能同时有值，两者只能选一个传值！当前入参：" + decData);
                    }


                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_prescription where certno=@certno";
                        cmd.Parameters.AddWithValue("@certno", certno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            List<FsiEpcRxAuthQueryOutputData> RxAuthQueryOutputData = new List<FsiEpcRxAuthQueryOutputData>();
                            foreach (DataRow row in dt.Rows)
                            {
                                FsiEpcRxAuthQueryOutputData item = new FsiEpcRxAuthQueryOutputData
                                {
                                    authRxno = row["auth_rxno"].ToString(),
                                    epcToken = row["epc_token"].ToString(),
                                    expiresIn = row["expires_in"].ToString(),
                                    fixmedinsCode = row["fixmedins_code"].ToString(),
                                    fixmedinsName = row["fixmedins_name"].ToString(),
                                    prscTime = row["prsc_time"].ToString(),
                                    diseCodg = row["dise_codg"].ToString(),
                                    diseName = row["dise_name"].ToString(),
                                    valiEndTime = row["valid_end_time"].ToString()
                                };
                                RxAuthQueryOutputData.Add(item);
                            }
                            /*出参加密*/
                            string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(RxAuthQueryOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                            /*加密结束*/
                            FsiEpcOutputList<FsiEpcRxAuthQueryOutputData> signDto = new FsiEpcOutputList<FsiEpcRxAuthQueryOutputData>
                            {
                                appId = FsiEpcTokeninfo.appId,
                                encType = "SM4",
                                signType = "SM2",
                                timestamp = fsiRequest.timestamp.ToString(),
                                data = RxAuthQueryOutputData,
                                version = version,
                                key = FsiEpcTokeninfo.appSecret,

                            };
                            Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(RxAuthQueryOutputData, Formatting.None));
                            Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                            //签名
                            string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                            /*---------------解密部分-----------------*/
                            string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                            Console.WriteLine("解密：" + eeee);
                            Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                            Console.WriteLine("验签：" + isVerify);
                            FsiEpcHeader FsiHeader = new FsiEpcHeader
                            {
                                code = 0,
                                appId = FsiEpcTokeninfo.appId,
                                encData = returnEncData,
                                signData = signData,
                                message = "success",
                                timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                    {
                        code = 50000,
                        message = $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace} " 
                    };
                    LogHelper.Error( $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 电子处方下载
        /// </summary>
        /// <returns></returns>
        [Route("fixmedins/rxInfoDld")]
        [HttpPost]
        public async Task<IHttpActionResult> rxInfoDld(HttpRequestMessage request)
        {
            DataTable dtinfo = new DataTable();
            DataTable dtdetail = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiEpcApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                    string encData = fsiRequest.encData;
                    string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    Console.WriteLine("处方中心入参解密：" + decData);

                    var RxInfoDldInput = JsonConvert.DeserializeObject<FsiRequestEpcRxInfoDldInput>(decData);
                    string authRxno = RxInfoDldInput.authRxno;
                    string epcToken = RxInfoDldInput.epcToken;

                    if (string.IsNullOrEmpty(authRxno) || string.IsNullOrEmpty(epcToken))
                    {
                        throw new Exception("参数校验失败：传入的电子处方令牌|医保处方授权编号为空，请检查入参！当前入参：" + decData);
                    }
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_prescription where  epc_token=@epc_token and auth_rxno=@auth_rxno";
                        cmd.Parameters.AddWithValue("@epc_token", epcToken);
                        cmd.Parameters.AddWithValue("@auth_rxno", authRxno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dtinfo.Load(reader);
                            if (dtinfo.Rows.Count == 0)
                            {
                                throw new Exception($"查询处方列表失败！处方授权编号：{authRxno} 未查询到处方列表，如需测试请联系管理员增加相关数据！");
                            }
                            cmd.Parameters.Clear();
                        }
                        cmd.CommandText = "select * from fsi_prescription_detail where   auth_rxno=@auth_rxno";
                        cmd.Parameters.AddWithValue("@auth_rxno", authRxno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            List<FsiEpcRxInfoDldOutputRxDetlList> dataList = new List<FsiEpcRxInfoDldOutputRxDetlList>();
                            dtdetail.Load(reader);
                            cmd.Parameters.Clear();
                            if (dtdetail.Rows.Count != 0)
                            {
                                foreach (DataRow row in dtdetail.Rows)
                                {
                                    FsiEpcRxInfoDldOutputRxDetlList item = new FsiEpcRxInfoDldOutputRxDetlList
                                    {
                                        medListCodg = row["med_list_codg"].ToString(),
                                        fixmedinsHilistId = row["fixmedins_hilist_id"].ToString(),
                                        hospPrepFlag = row["hosp_prep_flag"].ToString(),
                                        rxItemTypeCode = row["rx_item_type_code"].ToString(),
                                        rxItemTypeName = row["rx_item_type_name"].ToString(),
                                        tcmdrugTypeCode = row["tcmdrug_type_code"].ToString(),
                                        tcmdrugTypeName = row["tcmdrug_type_name"].ToString(),
                                        tcmherbFoote = row["tcmherb_foote"].ToString(),
                                        mednTypeCode = row["medn_type_code"].ToString(),
                                        mednTypeName = row["medn_type_name"].ToString(),
                                        mainMedcFlag = row["main_medc_flag"].ToString(),
                                        urgtFlag = row["urgt_flag"].ToString(),
                                        basMednFlag = row["bas_medn_flag"].ToString(),
                                        impDrugFlag = row["imp_drug_flag"].ToString(),
                                        drugProdname = row["drug_prodname"].ToString(),
                                        drugGenname = row["drug_genname"].ToString(),
                                        drugDosform = row["drug_dosform"].ToString(),
                                        drugSpec = row["drug_spec"].ToString(),
                                        prdrName = row["prdr_name"].ToString(),
                                        drugCnt = Convert.ToDecimal(row["drug_cnt"]),
                                        medcWayCodg = row["medc_way_codg"].ToString(),
                                        medcWayDscr = row["medc_way_dscr"].ToString(),
                                        medcEndtime = row["medc_endtime"].ToString(),
                                        medcBegntime = row["medc_begntime"].ToString(),
                                        medcDays = Convert.ToDecimal(row["medc_days"]),
                                        drugDosunt = row["drug_dosunt"].ToString(),
                                        sinDoscnt = Convert.ToDecimal(row["sin_doscnt"]),
                                        sinDosunt = row["sin_dosunt"].ToString(),
                                        usedFrquCodg = row["used_frqu_codg"].ToString(),
                                        usedFrquName = row["used_frqu_name"].ToString(),
                                        drugTotlcnt = row["drug_totlcnt"].ToString(),
                                        drugTotlcntEmp = row["drug_totlnt_emp"].ToString(),
                                        hospApprFlag = row["hosp_appr_flag"].ToString()
                                    };
                                    dataList.Add(item);
                                }
                                var RxInfoDldOutputData = new FsiEpcRxInfoDldOutputData
                                {
                                    hiRxno = dtinfo.Rows[0]["hi_rxno"].ToString(),
                                    fixmedinsCode = dtinfo.Rows[0]["fixmedins_code"].ToString(),
                                    fixmedinsName = dtinfo.Rows[0]["fixmedins_name"].ToString(),
                                    prscTime = dtinfo.Rows[0]["prsc_time"].ToString(),
                                    rxFile = dtinfo.Rows[0]["rx_file"].ToString(),
                                    rxTraceCode = dtinfo.Rows[0]["rx_trace_code"].ToString(),
                                    prscDeptName = dtinfo.Rows[0]["prsc_dept_name"].ToString(),
                                    rxTypeCode = dtinfo.Rows[0]["rx_type_code"].ToString(),
                                    rxTypeName = dtinfo.Rows[0]["rx_type_name"].ToString(),
                                    longRxFlag = dtinfo.Rows[0]["long_rx_flag"].ToString(),
                                    fileSuffix = dtinfo.Rows[0]["file_suffix"].ToString(),
                                    valiEndTime = dtinfo.Rows[0]["valid_end_time"].ToString(),
                                    rxDetlList = dataList,
                                    rxOtpinfo = new FsiEpcRxInfoDldOutputRxOtpinfo
                                    {
                                        medType = dtinfo.Rows[0]["med_type"].ToString(),
                                        patnName = dtinfo.Rows[0]["patn_name"].ToString(),
                                        //patnAge = Convert.ToDecimal(dtinfo.Rows[0]["patn_age"]),
                                        patnHgt = dtinfo.Rows[0]["patn_hgt"].ToString(),
                                        //patnWt = Convert.ToDecimal(dtinfo.Rows[0]["patn_wt"]),
                                        gend = dtinfo.Rows[0]["gend"].ToString(),
                                        //geso_val = Convert.ToDecimal(dtinfo.Rows[0]["geso_val"]),
                                        nwbFlag = dtinfo.Rows[0]["nwb_flag"].ToString(),
                                        nwbAge = dtinfo.Rows[0]["nwb_age"].ToString(),
                                        //suck_prd_flag = (int)dtinfo.Rows[0]["suck_prd_flag"],
                                        algsHis = dtinfo.Rows[0]["algs_his"].ToString(),
                                        diseCodg = dtinfo.Rows[0]["dise_codg"].ToString(),
                                        diseName = dtinfo.Rows[0]["dise_name"].ToString(),
                                        otpIptFlag = dtinfo.Rows[0]["otp_ipt_flag"].ToString(),
                                        maindiagCode = dtinfo.Rows[0]["main_diag_code"].ToString(),
                                        maindiagName = dtinfo.Rows[0]["main_diag_name"].ToString(),
                                        diseCondDscr = dtinfo.Rows[0]["dise_cond_dscr"].ToString()
                                    }

                                };

                                /*出参加密*/
                                string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(RxInfoDldOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                                /*加密结束*/
                                FsiEpcOutput<FsiEpcRxInfoDldOutputData> signDto = new FsiEpcOutput<FsiEpcRxInfoDldOutputData>
                                {
                                    appId = FsiEpcTokeninfo.appId,
                                    encType = "SM4",
                                    signType = "SM2",
                                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString(),
                                    data = RxInfoDldOutputData
                                };
                                Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(RxInfoDldOutputData, Formatting.None));
                                Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                                //签名
                                string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                                ///*---------------解密部分-----------------*/
                                string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                                Console.WriteLine("解密：" + eeee);
                                Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                                Console.WriteLine("验签：" + isVerify);
                                FsiEpcHeader FsiHeader = new FsiEpcHeader
                                {
                                    code = 0,
                                    appId = FsiEpcTokeninfo.appId,
                                    encData = returnEncData,
                                    signData = signData,
                                    message = "success",
                                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                                };
                                return Json(FsiHeader);

                            }
                            else
                            {
                                throw new Exception($"查询处方明细列表失败！处方授权编号：{authRxno} 未查询到处方药品列表，如需测试请联系管理员增加相关数据！");
                            }

                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                    {
                        code = 50000,
                        message = $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace} " 
                    };
                    LogHelper.Error( $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 电子处方信息核验
        /// </summary>
        /// <returns></returns>
        [Route("fixmedins/rxInfoVerify")]
        [HttpPost]
        public  IHttpActionResult rxInfoVerify(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiEpcApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                string encData = fsiRequest.encData;
                string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("处方中心入参解密：" + decData);

                var RxInfoVerifyOutputData = new FsiEpcRxInfoVerifyOutputData
                {
                    flag = true,
                    rxSignVerifySn = "rxSignVerifySn1234567890",
                    signCertDn = "signCertDn1234567890",
                    signCertSn = "signCertSn1234567890"
                };

                /*出参加密*/
                string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(RxInfoVerifyOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                /*加密结束*/
                FsiEpcOutput<FsiEpcRxInfoVerifyOutputData> signDto = new FsiEpcOutput<FsiEpcRxInfoVerifyOutputData>
                {
                    appId = FsiEpcTokeninfo.appId,
                    encType = "SM4",
                    signType = "SM2",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString(),
                    data = RxInfoVerifyOutputData
                };
                Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(RxInfoVerifyOutputData, Formatting.None));
                Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                //签名
                string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                ///*---------------解密部分-----------------*/
                string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("解密：" + eeee);
                Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                Console.WriteLine("验签：" + isVerify);
                FsiEpcHeader FsiHeader = new FsiEpcHeader
                {
                    code = 0,
                    appId = FsiEpcTokeninfo.appId,
                    encData = returnEncData,
                    signData = signData,
                    message = "success",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                {
                    code = 50000,
                    message = $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace} " 
                };
                LogHelper.Error( $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 电子处方审核信息上传
        /// </summary>
        /// <returns></returns>
        [Route("fixmedins/rxChkUpld")]
        [HttpPost]
        public IHttpActionResult rxChkUpld(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiEpcApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                string encData = fsiRequest.encData;
                string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("处方中心入参解密：" + decData);

                var RxChkUpldOutputData = new FsiEpcRxChkUpldOutputData
                {
                    flag = true,
                    rxChkBizSn = "rxChkBizSn1234567890",
                };

                /*出参加密*/
                string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(RxChkUpldOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                /*加密结束*/
                FsiEpcOutput<FsiEpcRxChkUpldOutputData> signDto = new FsiEpcOutput<FsiEpcRxChkUpldOutputData>
                {
                    appId = FsiEpcTokeninfo.appId,
                    encType = "SM4",
                    signType = "SM2",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString(),
                    data = RxChkUpldOutputData
                };
                Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(RxChkUpldOutputData, Formatting.None));
                Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                //签名
                string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                ///*---------------解密部分-----------------*/
                string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("解密：" + eeee);
                Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                Console.WriteLine("验签：" + isVerify);
                FsiEpcHeader FsiHeader = new FsiEpcHeader
                {
                    code = 0,
                    appId = FsiEpcTokeninfo.appId,
                    encData = returnEncData,
                    signData = signData,
                    message = "success",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                {
                    code = 50000,
                    message = $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace} " 
                };
                LogHelper.Error( $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 药品销售出库明细上传
        /// </summary>
        /// <returns></returns>
        [Route("fixmedins/rxSelDrugUpld")]
        [HttpPost]
        public IHttpActionResult rxSelDrugUpld(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiEpcApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }
                Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                string encData = fsiRequest.encData;
                string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("处方中心入参解密：" + decData);

                var RxSelDrugUpldOutputData = new FsiEpcRxSelDrugUpldOutputData
                {
                    flag = true
                };

                /*出参加密*/
                string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(RxSelDrugUpldOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                /*加密结束*/
                FsiEpcOutput<FsiEpcRxSelDrugUpldOutputData> signDto = new FsiEpcOutput<FsiEpcRxSelDrugUpldOutputData>
                {
                    appId = FsiEpcTokeninfo.appId,
                    encType = "SM4",
                    signType = "SM2",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString(),
                    data = RxSelDrugUpldOutputData
                };
                Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(RxSelDrugUpldOutputData, Formatting.None));
                Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                //签名
                string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                ///*---------------解密部分-----------------*/
                string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                Console.WriteLine("解密：" + eeee);
                Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                Console.WriteLine("验签：" + isVerify);
                FsiEpcHeader FsiHeader = new FsiEpcHeader
                {
                    code = 0,
                    appId = FsiEpcTokeninfo.appId,
                    encData = returnEncData,
                    signData = signData,
                    message = "success",
                    timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                {
                    code = 50000,
                    message = $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace} " 
                };
                return Json(FsiHeader);
            }
        }
        
        /// <summary>
        /// 定点医药机构药品库存价格同步
        /// </summary>
        /// <returns></returns>
        [Route("fixmedinsInvMgr/drugListBatchSync")]
        [Route("fixmedins/drugListBatchSync")]
        [Route("drugListBatchSync")]
        [HttpPost]
        public async Task<IHttpActionResult>  drugListBatchSync(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiEpcApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }

                    Console.WriteLine("处方中心入参："+ request.Content.ReadAsStringAsync().Result);
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                    string encData = fsiRequest.encData;
                    string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    string version = fsiRequest.version;
                    string timestamp = fsiRequest.timestamp.ToString();
                    Console.WriteLine("处方中心入参解密：" + decData);

                    var drugListBatchSyncInput = JsonConvert.DeserializeObject<FsiRequestEpcDrugListBatchSyncInput>(decData);
                    if(drugListBatchSyncInput.fixMedinsDrugUpdateDTOList ==null || drugListBatchSyncInput.fixMedinsDrugUpdateDTOList.Count == 0)
                    {
                        throw new Exception("参数校验失败：传入的商品库存列表为空");
                    }
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        List<string> errorFixmedinsHilistIdList = new List<string>();
                        foreach (var item in drugListBatchSyncInput.fixMedinsDrugUpdateDTOList)
                        {
                            string fixmedinsHilistId = item.fixmedinsHilistId;
                            string fixmedinsCode = item.fixmedinsCode;
                            try
                            {
                                DataTable dt = new DataTable();
                                cmd.CommandText = "select * from fsi_epcdrugstorestocks where fixmedinsCode = @fixmedinsCode and fixmedinsHilistId = @fixmedinsHilistId";
                                cmd.Parameters.AddWithValue("@fixmedinsCode", fixmedinsCode);
                                cmd.Parameters.AddWithValue("@fixmedinsHilistId", fixmedinsHilistId);
                                using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                                {
                                    dt.Load(reader);
                                    cmd.Parameters.Clear();
                                    if (dt.Rows.Count == 0)
                                    {
                                        cmd.CommandText = "insert into fsi_epcdrugstorestocks(fixmedinsHilistId,fixmedinsCode,medListCodg,stasCodg,stasName,selPric,inv,create_time,update_time) values (@fixmedinsHilistId,@fixmedinsCode,@medListCodg,@stasCodg,@stasName,@selPric,@inv,now(),now())";
                                        cmd.Parameters.AddWithValue("@fixmedinsHilistId", fixmedinsHilistId);
                                        cmd.Parameters.AddWithValue("@fixmedinsCode", fixmedinsCode);
                                        cmd.Parameters.AddWithValue("@medListCodg", item.medListCodg);
                                        cmd.Parameters.AddWithValue("@stasCodg", item.stasCodg);
                                        cmd.Parameters.AddWithValue("@stasName", item.stasName);
                                        cmd.Parameters.AddWithValue("@selPric", item.selPric);
                                        cmd.Parameters.AddWithValue("@inv", item.inv);
                                        await cmd.ExecuteNonQueryAsync();
                                        cmd.Parameters.Clear();
                                    }
                                    else
                                    {
                                        cmd.CommandText = "update fsi_epcdrugstorestocks set  stasCodg =@stasCodg,stasName =@stasName, selPric= @selPric,inv = @inv,update_time = now() where fixmedinsCode = @fixmedinsCode and fixmedinsHilistId = @fixmedinsHilistId ";
                                        cmd.Parameters.AddWithValue("@fixmedinsHilistId", fixmedinsHilistId);
                                        cmd.Parameters.AddWithValue("@fixmedinsCode", fixmedinsCode);
                                        cmd.Parameters.AddWithValue("@medListCodg", item.medListCodg);
                                        cmd.Parameters.AddWithValue("@stasCodg", item.stasCodg);
                                        cmd.Parameters.AddWithValue("@stasName", item.stasName);
                                        cmd.Parameters.AddWithValue("@selPric", item.selPric);
                                        cmd.Parameters.AddWithValue("@inv", item.inv);
                                        await cmd.ExecuteNonQueryAsync();
                                        cmd.Parameters.Clear();
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Error($"[fixmedinsInvMgr/drugListBatchSync]处方中心保存定点机构库存信息失败！机构代码：{fixmedinsCode} 定点机构目录编码：{fixmedinsHilistId} 错误信息：{ex.Message}  异常来源：{ex.StackTrace}");
                                errorFixmedinsHilistIdList.Add(fixmedinsHilistId);
                            }
                        }

                        var drugListBatchSyncOutputData = new FsiEpcDrugListBatchSyncOutputData()
                        {
                            flag = true,
                            disMatchFixListCodes = errorFixmedinsHilistIdList
                        };
                        /*出参加密*/
                        string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(drugListBatchSyncOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                        /*加密结束*/
                        FsiEpcOutput<FsiEpcDrugListBatchSyncOutputData> signDto = new FsiEpcOutput<FsiEpcDrugListBatchSyncOutputData>
                        {
                            appId = FsiEpcTokeninfo.appId,
                            encType = "SM4", 
                            signType = "SM2",
                            timestamp = fsiRequest.timestamp.ToString(),
                            data = drugListBatchSyncOutputData,
                            version = version,
                            key = FsiEpcTokeninfo.appSecret,

                        };
                            Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(drugListBatchSyncOutputData, Formatting.None));
                            Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                            //签名
                            string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                            /*---------------解密部分-----------------*/
                            string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                            Console.WriteLine("解密：" + eeee);
                            Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                            Console.WriteLine("验签：" + isVerify);
                            FsiEpcHeader FsiHeader = new FsiEpcHeader
                            {
                                code = 0,
                                appId = FsiEpcTokeninfo.appId,
                                encData = returnEncData,
                                signData = signData,
                                message = "success",
                                timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                            };
                            return Json(FsiHeader);    
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                    {
                        code = 50000,
                        message = $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace} " 
                    };
                    LogHelper.Error( $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 定点医药机构药品库存信息查询
        /// </summary>
        /// <returns></returns>
        [Route("fixmedinsInvMgr/drugInfoListQuery")]
        [Route("fixmedins/drugInfoListQuery")]
        [HttpPost]
        public async Task<IHttpActionResult> drugInfoListQuery(HttpRequestMessage request)
        {
            DataTable dt = new DataTable();
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiEpcApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }

                    Console.WriteLine("处方中心入参："+ request.Content.ReadAsStringAsync().Result);
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                    string encData = fsiRequest.encData;
                    string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    string version = fsiRequest.version;
                    string timestamp = fsiRequest.timestamp.ToString();
                    Console.WriteLine("处方中心入参解密：" + decData);

                    var drugInfoListQueryInput = JsonConvert.DeserializeObject<FsiRequestEpcDrugInfoListQueryInput>(decData);
                    int pageNum = drugInfoListQueryInput.pageNum;
                    int pageSize = drugInfoListQueryInput.pageSize;
                    
                    if (pageNum <= 0 || pageSize <= 0)
                    {
                        throw new Exception("参数校验失败：分页参数错误！pageNum和pageSize必须大于0！");
                    }
                    //当前分页的最大页数
                    int maxpage = (int)((pageNum - 1) * pageSize);
                    
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select a.medListCodg,a.fixmedinsHilistId,a.fixmedinsCode,b.REG_NAME,b.DRUG_PRODNAME,b.DRUG_SPEC,b.PRODENTP_NAME,b.DRUG_DOSFORM,b.APRVNO,a.stasCodg,a.stasName,a.selPric,a.inv,b.OTC_FLAG,b.DRUGSTDCODE from fsi_epcdrugstorestocks a left join  ml_xyzcyml b on a.medListCodg = b.med_list_codg where a.fixmedinsCode=@fixmedinsCode ";
                        var parameters = new List<MySqlParameter>();

                        if (!string.IsNullOrEmpty(drugInfoListQueryInput.medListCodg))
                        {
                            cmd.CommandText += " and a.medListCodg=@medListCodg";
                            parameters.Add(new MySqlParameter("@medListCodg", $"%{drugInfoListQueryInput.medListCodg}%"));
                        }

                        if (!string.IsNullOrEmpty(drugInfoListQueryInput.fixmedinsHilistId))
                        {
                            cmd.CommandText += " and a.fixmedinsHilistId=@fixmedinsHilistId";
                            parameters.Add(new MySqlParameter("@fixmedinsHilistId", $"%{drugInfoListQueryInput.fixmedinsHilistId}%"));
                        }

                        if (!string.IsNullOrEmpty(drugInfoListQueryInput.lastUpdtTime))
                        {
                            cmd.CommandText += " and a.update_time>=@lastUpdtTime";
                            parameters.Add(new MySqlParameter("@lastUpdtTime", $"%{drugInfoListQueryInput.lastUpdtTime}%"));
                        }
                        
                        cmd.CommandText += " limit @maxpage,@pageSize";
                        parameters.Add(new MySqlParameter("@maxpage", maxpage));
                        parameters.Add(new MySqlParameter("@pageSize", pageSize));
                        
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            List<FsiEpcDrugInfoDrugInfoListQueryOutputList> druglist = new List<FsiEpcDrugInfoDrugInfoListQueryOutputList>();
                            foreach (DataRow row in dt.Rows)
                            {
                                FsiEpcDrugInfoDrugInfoListQueryOutputList item = new FsiEpcDrugInfoDrugInfoListQueryOutputList
                                {
                                    medListCodg = row["medListCodg"].ToString(), //医保药品编码
                                    fixmedinsHilistId = row["fixmedinsHilistId"].ToString(), //定点医药机构目录编码
                                    fixmedinsCode = row["fixmedinsCode"].ToString(), //定点医药机构编码
                                    genname = row["REG_NAME"].ToString(), //通用名称
                                    prodname = row["DRUG_PRODNAME"].ToString(), //商品名称
                                    drugName = row["REG_NAME"].ToString(), //通用名称
                                    spec = row["DRUG_SPEC"].ToString(), //规格
                                    prdr =row["PRODENTP_NAME"].ToString(), //生产企业
                                    dosform= row["DRUG_DOSFORM"].ToString(), //剂型
                                    aprvno = row["APRVNO"].ToString(), //批准文号 注册证号
                                    stasCode = row["stasCodg"].ToString(), //库存状态编码
                                    stasName = row["stasName"].ToString(), //库存状态名称
                                    selPric = int.Parse(row["selPric"].ToString()), //销售价格
                                    inv = int.Parse(row["inv"].ToString()), //库存
                                    rxFlag = int.Parse(row["OTC_FLAG"].ToString()),//处方标志
                                    drugstdcode = row["DRUGSTDCODE"].ToString()//药品本位码
                                };
                                druglist.Add(item);
                            }
                            cmd.CommandText = "select count(*) from fsi_epcdrugstorestocks a left join  ml_xyzcyml b on a.medListCodg = b.med_list_codg where a.fixmedinsCode=@fixmedinsCode ";
                            int count = (int)await cmd.ExecuteScalarAsync();
                            var pageCount = (int)Math.Ceiling((double)count / (double)pageSize);
                            var drugInfoDrugInfoListQueryOutputData = new FsiEpcDrugInfoListQueryOutputData()
                            {
                                total = count,
                                size = pageSize,
                                pages = pageCount, 
                                list = druglist
                            };
                            /*出参加密*/
                            string returnEncData = SMUtil.encrypt(JsonConvert.SerializeObject(drugInfoDrugInfoListQueryOutputData, Formatting.None), FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                            /*加密结束*/
                            FsiEpcOutput<FsiEpcDrugInfoListQueryOutputData> signDto = new FsiEpcOutput<FsiEpcDrugInfoListQueryOutputData>
                            {
                                appId = FsiEpcTokeninfo.appId,
                                encType = "SM4",
                                signType = "SM2",
                                timestamp = fsiRequest.timestamp.ToString(),
                                data = drugInfoDrugInfoListQueryOutputData,
                                version = version,
                                key = FsiEpcTokeninfo.appSecret,

                            };
                            Console.WriteLine("准备签名验证参数：" + JsonConvert.SerializeObject(drugInfoDrugInfoListQueryOutputData , Formatting.None));
                            Console.WriteLine("完整的signDto参数：" + JsonConvert.SerializeObject(signDto, Formatting.None));
                            //签名
                            string signData = SMUtil.sign(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.privateKey);

                            /*---------------解密部分-----------------*/
                            string eeee = SMUtil.decrypt(returnEncData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                            Console.WriteLine("解密：" + eeee);
                            Boolean isVerify = SMUtil.verify(JsonConvert.SerializeObject(signDto, Formatting.None), FsiEpcTokeninfo.appSecret, FsiEpcTokeninfo.publicKey, signData);
                            Console.WriteLine("验签：" + isVerify);
                            FsiEpcHeader FsiHeader = new FsiEpcHeader
                            {
                                code = 0,
                                appId = FsiEpcTokeninfo.appId,
                                encData = returnEncData,
                                signData = signData,
                                message = "success",
                                timestamp = PublicMethod.ConvertToUnixTimestampMillis(DateTime.Now).ToString()

                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    FsiEpcErrorHeader FsiHeader = new FsiEpcErrorHeader
                    {
                        code = 50000,
                        message = $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace} " 
                    };
                    LogHelper.Error( $"[{Errnum}]调用国标处方中心自定义服务失败！请检查！错误内容：处方中心接口异常！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 处方中心解密测试接口
        /// </summary>
        /// <param name="request">test</param>
        /// <returns></returns>
        [Route("fixmedins/Test")]
        [HttpPost]
        public async Task<IHttpActionResult> Test(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiEpcApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    Console.WriteLine("处方中心入参：" + request.Content.ReadAsStringAsync().Result);
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEpcHeader>(request.Content.ReadAsStringAsync().Result);
                    string encData = fsiRequest.encData;
                    string decData = SMUtil.decrypt(encData, FsiEpcTokeninfo.appId, FsiEpcTokeninfo.appSecret);
                    Console.WriteLine("解密：" + decData);
                    return Ok(decData);

                }
                catch (Exception ex)
                {
                    return Json(ex);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
    }
}
